package com.zzx.resource.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 配置 Jwt 方式 资源服务器自己解析token
 **/
@Configuration
public class TokenConfig {
    private static String SIGNING_KEY = "test";
    @Autowired
    private MyUserAuthenticationConverter myUserAuthenticationConverter;

    /**
     * 实际上不用配置了，通过yml 文件中配置 秘钥即可
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        /*JwtAccessTokenConverter converter = new JwtAccessTokenConverter(){
            @Override
            protected Map<String, Object> decode(String token) {
                Map<String, Object> decode = super.decode(token);
                Integer userType = Integer.valueOf(JSON.toJSONString(decode.get("user_type")));
                String userId = String.valueOf(decode.get("user_id"));
                String userName = String.valueOf(decode.get("user_name"));
                String authoritiesStr= String.valueOf(decode.get("authorities"));
                List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesStr);
                LoginUser loginUser = new LoginUser(userId,userType,userName,"N/A",grantedAuthorities);
                //将用户信息和权限填充 到用户身份token对象中
               *//* UsernamePasswordAuthenticationToken authenticationToken
                        = new UsernamePasswordAuthenticationToken(loginUser,null,grantedAuthorities);
                //将authenticationToken填充到安全上下文
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);*//*
                decode.put("user_name", loginUser);
                return decode;
            }
        };*/
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
        defaultAccessTokenConverter.setUserTokenConverter(myUserAuthenticationConverter);
        converter.setSigningKey(SIGNING_KEY);
        converter.setAccessTokenConverter(defaultAccessTokenConverter);
        return converter;
    }

}
